package sk.uniza.fri.cerviix.client;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;

import javax.swing.JOptionPane;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import sk.uniza.fri.cerviix.client.network.NetworkManager;

public class Client
{
	public static final String NAME = "CerviiX";
	public static final Logger log = Logger.getLogger(NAME);
	
	static
	{
		StreamHandler handler = new StreamHandler(System.out, new SimpleFormatter());
		handler.setFormatter(new SimpleFormatter());
		
		log.addHandler(handler);
		log.setLevel(Level.ALL);
		
		log.info("Logger connected.");
	}
	
	public static void main(String[] arguments)
	{		
		try
		{
			new Client();
		}
		catch (LWJGLException e)
		{
			Client.log.severe("LWJGL subsystem failed, can't start client.");
		}
	}
	
	private NetworkManager networkManager;
	
	public Client() throws LWJGLException
	{
		Display.setDisplayMode(new DisplayMode(Game.RESOLUTION_HORIZONTAL, Game.RESOLUTION_VERTICAL));
		Display.setTitle("CerviiX");
		Display.create();
		
		networkManager = new NetworkManager();
		
		String ipAddress, playerName;
		
		playerName = JOptionPane.showInputDialog(null, "Enter your name:", "CerviiX", JOptionPane.QUESTION_MESSAGE);
		ipAddress = JOptionPane.showInputDialog(null, "Enter server address:", "CerviiX", JOptionPane.QUESTION_MESSAGE);
		
		if (playerName.equals("") || ipAddress.equals(""))
		{
			shutdown();
			return;
		}
		
		playerName = playerName.toLowerCase();
		
		Game game = null;
		
		try
		{
			game = new Game(networkManager, playerName);
		}
		catch (IOException e)
		{
			Client.log.severe("Can't load resource.");
			
			shutdown();
			return;
		}
		
		try
		{
			networkManager.connect(ipAddress);
			
			try
			{
				game.run();
			}
			catch (IOException e)
			{
				Client.log.severe("Player was disconnected.");
				
				JOptionPane.showMessageDialog(null, "You were disconnected", "Network problem", JOptionPane.WARNING_MESSAGE);
			}
		}
		catch (IOException e)
		{
			Client.log.severe("Connect to server failed.");
			
			JOptionPane.showMessageDialog(null, "Can$t connect to server. Maybe you typed IP adress incorrect.", "Network problem", JOptionPane.WARNING_MESSAGE);
		}
		
		shutdown();
	}
	
	private void shutdown()
	{
		Client.log.info("Shutting down...");
		
		Display.destroy();
		
		try
		{
			Thread.sleep(3000);
		}
		catch (InterruptedException e)
		{
		}
		
		networkManager.disconnect();
	}
}
